package com.example.treehole.service

import android.content.Context
import android.net.Uri
import android.util.Log
import com.example.treehole.ui.component.showLoginSnackbar
import com.example.treehole.ui.component.showTreeholeSnackbar
import com.example.treehole.ui.model.Comment
import com.example.treehole.ui.model.PostDetail
import com.example.treehole.ui.model.PostInfo
import com.example.treehole.ui.model.UserInfo
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody.Companion.toRequestBody

object DataRepository {
    private val apiService = NetworkClient.apiService

    // 发送验证码
    suspend fun sendVerifyCode(userEmail: String): Boolean {
        return withContext(Dispatchers.IO) {
            val res = apiService.sendVerifyCode(
                ApiService.VerifyRequest(userEmail)
            )
            res.body()?.let { apiResponse ->
                if (apiResponse.code == 0) {
                    showLoginSnackbar(apiResponse.msg)
                    false
                } else {
                    showLoginSnackbar("验证码已发送")
                    true
                }
            } ?: run {
                showLoginSnackbar("网络请求失败，请重试")
                false
            }
        }
    }

    // 用户注册
    suspend fun registerUser(
        userEmail: String,
        password: String,
        verifyCode: String
    ): UserInfo? {
        return withContext(Dispatchers.IO) {
            val res = apiService.registerUser(
                ApiService.RegisterRequest(userEmail, password, verifyCode)
            )
            res.body()?.let { apiResponse ->
                if (apiResponse.code == 1) {
                    apiResponse.data
                } else {
                    showLoginSnackbar(apiResponse.msg)
                    null
                }
            } ?: run {
                showLoginSnackbar("网络请求失败，请重试")
                null
            }
        }
    }

    // 修改密码
    suspend fun modifyPassword(
        userEmail: String,
        newPassword: String,
        verifyCode: String
    ): Boolean {
        return withContext(Dispatchers.IO) {
            val res = apiService.modifyPassword(
                ApiService.ModifyPassWordRequest(userEmail, newPassword, verifyCode)
            )
            res.body()?.let { apiResponse ->
                if (apiResponse.code == 0) {
                    showLoginSnackbar(apiResponse.msg)
                    false
                } else {
                    showLoginSnackbar("密码修改成功")
                    true
                }
            } ?: run {
                showLoginSnackbar("网络请求失败，请重试")
                false
            }
        }
    }

    // 密码登录
    suspend fun loginByPassword(
        userEmail: String,
        password: String
    ): UserInfo? {
        return withContext(Dispatchers.IO) {
            val res = apiService.loginByPassword(
                ApiService.LoginByPasswordRequest(userEmail, password)
            )
            res.body()?.let { apiResponse ->
                if (apiResponse.code == 0) {
                    showLoginSnackbar(apiResponse.msg)
                    null
                } else {
                    apiResponse.data
                }
            } ?: run {
                showLoginSnackbar("网络请求失败，请重试")
                null
            }
        }
    }

    // 验证码登录
    suspend fun loginByVerify(
        userEmail: String,
        verifyCode: String
    ): UserInfo? {
        return withContext(Dispatchers.IO) {
            val res = apiService.loginByVerify(
                ApiService.LoginByVerifyRequest(userEmail, verifyCode)
            )
            res.body()?.let { apiResponse ->
                if (apiResponse.code == 0) {
                    showLoginSnackbar(apiResponse.msg)
                    null
                } else {
                    apiResponse.data
                }
            } ?: run {
                showLoginSnackbar("网络请求失败，请重试")
                null
            }
        }
    }

    // 点赞内容
    suspend fun likePost(
        token: String,
        postId: Int,
        userId: Int
    ): Boolean {
        return withContext(Dispatchers.IO) {
            val res = apiService.likePost(
                token,
                ApiService.ActionOnPostRequest(postId, userId)
            )
            res.body()?.let { apiResponse ->
                if (apiResponse.code == 0) {
                    showTreeholeSnackbar(apiResponse.msg)
                    false
                } else {
                    true
                }
            } ?: run {
                showTreeholeSnackbar("网络请求失败，请重试")
                false
            }
        }
    }

    // 取消点赞内容
    suspend fun unlikePost(
        token: String,
        postId: Int,
        userId: Int
    ): Boolean {
        return withContext(Dispatchers.IO) {
            Log.d("TestCommunicate", "hereInDataRepository")
            val res = apiService.unlikePost(
                token,
                ApiService.ActionOnPostRequest(postId, userId)
            )
            res.body()?.let { apiResponse ->
                if (apiResponse.code == 0) {
                    showTreeholeSnackbar(apiResponse.msg)
                    false
                } else {
                    true
                }
            } ?: run {
                showTreeholeSnackbar("网络请求失败，请重试")
                false
            }
        }
    }

    // 收藏内容
    suspend fun favoritePost(
        token: String,
        postId: Int,
        userId: Int
    ): Boolean {
        return withContext(Dispatchers.IO) {
            val res = apiService.favoritePost(
                token,
                ApiService.ActionOnPostRequest(postId,userId)
                )
            res.body()?.let { apiResponse ->
                if (apiResponse.code == 0) {
                    showTreeholeSnackbar(apiResponse.msg)
                    false
                } else {
                    true
                }
            } ?: run {
                showTreeholeSnackbar("网络请求失败，请重试")
                false
            }
        }
    }

    // 取消收藏内容
    suspend fun unfavoritePost(
        token: String,
        postId: Int,
        userId: Int
    ): Boolean {
        return withContext(Dispatchers.IO) {
            val res = apiService.unfavoritePost(
                token,
                ApiService.ActionOnPostRequest(postId,userId)
            )
            res.body()?.let { apiResponse ->
                if (apiResponse.code == 0) {
                    showTreeholeSnackbar(apiResponse.msg)
                    false
                } else {
                    true
                }
            } ?: run {
                showTreeholeSnackbar("网络请求失败，请重试")
                false
            }
        }
    }

    // 点赞评论
    suspend fun likeCmt(
        token: String,
        cmtId: Int,
        userId: Int
    ): Boolean {
        return withContext(Dispatchers.IO) {
            val res = apiService.likeCmt(
                token,
                ApiService.ActionOnCmtRequest(cmtId,userId)
            )
            res.body()?.let { apiResponse ->
                if (apiResponse.code == 0) {
                    showTreeholeSnackbar(apiResponse.msg)
                    false
                } else {
                    true
                }
            } ?: run {
                showTreeholeSnackbar("网络请求失败，请重试")
                false
            }
        }
    }

    // 取消点赞评论
    suspend fun unlikeCmt(
        token: String,
        cmtId: Int,
        userId: Int
    ): Boolean {
        return withContext(Dispatchers.IO) {
            val res = apiService.unlikeCmt(
                token,
                ApiService.ActionOnCmtRequest(cmtId,userId)
            )
            res.body()?.let { apiResponse ->
                if (apiResponse.code == 0) {
                    showTreeholeSnackbar(apiResponse.msg)
                    false
                } else {
                    true
                }
            } ?: run {
                showTreeholeSnackbar("网络请求失败，请重试")
                false
            }
        }
    }

    // 搜索帖子
    suspend fun searchPost(
        token: String,
        query: String,
        userId: Int,
        tag: Int
    ): List<PostInfo>? {
        return withContext(Dispatchers.IO) {
            val res = apiService.searchPost(
                token,
                ApiService.SearchPostRequest(query,userId, tag)
            )
            res.body()?.let { apiResponse ->
                if (apiResponse.code == 0) {
                    showTreeholeSnackbar(apiResponse.msg)
                    null
                } else {
                    apiResponse.data
                }
            } ?: run {
                showTreeholeSnackbar("网络请求错误，请重试")
                null
            }
        }
    }

    // 上传图片
    suspend fun uploadImage(
        context: Context,
        token: String,
        imageUri: Uri
    ): String? {
        val contentResolver = context.contentResolver
        val inputStream = contentResolver.openInputStream(imageUri)
        val bytes = inputStream?.readBytes() ?: ByteArray(0)
        val filePart = MultipartBody.Part.createFormData(
            "image",
            "image.jpg",
            bytes.toRequestBody("image/jpeg".toMediaTypeOrNull())
        )
        return withContext(Dispatchers.IO) {
            val res = apiService.uploadImage(token, filePart)
            res.body()?.let { apiResponse ->
                if (apiResponse.code == 0) {
                    showTreeholeSnackbar(apiResponse.msg)
                    null
                } else {
                    apiResponse.data
                }
            } ?: run {
                showTreeholeSnackbar("网络请求错误，请重试")
                null
            }
        }
    }

    // 发布帖子
    suspend fun createPost(
        token: String,
        userId: Int,
        title: String,
        content: String,
        pics: List<String>,
        tag: Int
    ): Int? {
        return withContext(Dispatchers.IO) {
            val res = apiService.createPost(
                token,
                ApiService.CreatePostRequest(userId, title, content, pics, tag)
            )
            res.body()?.let { apiResponse ->
                if (apiResponse.code == 0) {
                    showTreeholeSnackbar(apiResponse.msg)
                    null
                } else {
                    apiResponse.data
                }
            }
        } ?: run {
            showTreeholeSnackbar("网络请求错误，请重试")
            null
        }
    }

    // 发布评论
    suspend fun createCmt(
        token: String,
        userId: Int,
        postId: Int,
        type: Int,
        cmtCmtId: Int,
        replyUserName: String,
        content: String
    ): Comment? {
        return withContext(Dispatchers.IO) {
            val res = apiService.createCmt(
                token,
                ApiService.CreateCmtRequest(userId, postId, type, cmtCmtId, replyUserName, content)
            )
            res.body()?.let { apiResponse ->
                if (apiResponse.code == 0) {
                    showTreeholeSnackbar(apiResponse.msg)
                    null
                } else {
                    apiResponse.data
                }
            } ?: run {
                showTreeholeSnackbar("网络请求错误，请重试")
                null
            }
        }
    }

    // 查看树洞最新页
    suspend fun askNewPost(
        token: String,
        userId: Int,
        tagId: Int,
        page: Int
    ): List<PostInfo>? {
        return withContext(Dispatchers.IO) {
            val res = apiService.askNewPost(
                token,
                ApiService.AskNewPostRequest(userId, tagId, page)
            )
            res.body()?.let { apiResponse ->
                if (apiResponse.code == 0) {
                    showTreeholeSnackbar(apiResponse.msg)
                    null
                } else {
                    apiResponse.data
                }
            } ?: run {
                showTreeholeSnackbar("网络请求错误，请重试")
                null
            }
        }
    }

    // 查看树洞热门页
    suspend fun askHotPost(
        token: String,
        userId: Int
    ): List<PostInfo>? {
        return withContext(Dispatchers.IO) {
            val res = apiService.askHotPost(
                token,
                ApiService.AskHotPostRequest(userId)
            )
            res.body()?.let { apiResponse ->
                if (apiResponse.code == 0) {
                    showTreeholeSnackbar(apiResponse.msg)
                    null
                } else {
                    apiResponse.data
                }
            } ?: run {
                showTreeholeSnackbar("网络请求错误，请重试")
                null
            }
        }
    }

    // 获取帖子详情
    suspend fun askPostDetail(
        token: String,
        postId: Int,
        userId: Int
    ): PostDetail? {
        return withContext(Dispatchers.IO) {
            val res = apiService.askPostDetail(
                token,
                ApiService.ActionOnPostRequest(postId, userId)
            )
            res.body()?.let { apiResponse ->
                if (apiResponse.code == 0) {
                    showTreeholeSnackbar(apiResponse.msg)
                    null
                } else {
                    apiResponse.data
                }
            } ?: run {
                showTreeholeSnackbar("网络请求错误，请重试")
                null
            }
        }
    }

    // 查看个人帖子
    suspend fun getMyPosts(
        token: String,
        userId: Int,
        page: Int
    ): List<PostInfo>? {
        return withContext(Dispatchers.IO) {
            val res = apiService.getMyPosts(
                token,
                ApiService.GetListRequest(userId,page)
            )
            res.body()?.let { apiResponse ->
                if (apiResponse.code == 0) {
                    showTreeholeSnackbar(apiResponse.msg)
                    null
                } else {
                    apiResponse.data
                }
            } ?: run {
                showTreeholeSnackbar("网络请求错误，请重试")
                null
            }
        }
    }

    // 查看个人收藏
    suspend fun getMyFavoritePosts(
        token: String,
        userId: Int,
        page: Int
    ): List<PostInfo>? {
        return withContext(Dispatchers.IO) {
            val res = apiService.getMyFavoritePosts(
                token,
                ApiService.GetListRequest(userId, page)
            )
            res.body()?.let { apiResponse ->
                if (apiResponse.code == 0) {
                    showTreeholeSnackbar(apiResponse.msg)
                    null
                } else {
                    apiResponse.data
                }
            } ?: run {
                showTreeholeSnackbar("网络请求错误，请重试")
                null
            }
        }
    }

    // 查看个人评论
    suspend fun getMyComments(
        token: String,
        userId: Int,
        page: Int
    ): List<Comment>? {
        return withContext(Dispatchers.IO) {
            val res = apiService.getMyComments(
                token,
                ApiService.GetListRequest(userId, page)
            )
            res.body()?.let { apiResponse ->
                if (apiResponse.code == 0) {
                    showTreeholeSnackbar(apiResponse.msg)
                    null
                } else {
                    apiResponse.data
                }
            } ?: run {
                showTreeholeSnackbar("网络请求错误，请重试")
                null
            }
        }
    }
}
